/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testing.jee.web.view;

import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.data.validator.RegexpValidator;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.Notification;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import testing.jee.ejb.RequestBean;
import testing.jee.entity.User;
import testing.jee.web.View;

/**
 *
 * @author nova
 */
@org.springframework.stereotype.Component
@Scope(value="session")
public class NewUserView extends HorizontalLayout implements View {

    @Autowired
    RequestBean req;
    private Form userForm = new Form();
    private User user;
    private Table userListTable = new Table();
    private IndexedContainer userList = new IndexedContainer();
    private String[] visibleItems = {"id"};
    private String[] visibleItem = {"Username"};
    private Window deleteDialogueWindow = new Window("Delete User");
    private String selectedUserId = "";
    Label reallyDeleteLabel = new Label();

    @PostConstruct
    public void init() {
        userForm.setCaption("New User");
        userForm.setWriteThrough(false);
        userForm.setInvalidCommitted(false);
        userForm.setFormFieldFactory(new UserFieldFactory());
        setSpacing(true);

        addComponent(userListTable);
        initUserList();
        initUserListTable();
        user = new User();
        BeanItem<User> userBeanItem = new BeanItem<User>(user, visibleItems);
        userForm.setItemDataSource(userBeanItem);
        
        Button submitButton = new Button();
        submitButton.setCaption("Add");
        submitButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                userForm.commit();
                req.createUser(user);
                user = new User();
                userForm.setItemDataSource(new BeanItem<User>(user, visibleItems));
                initUserList();
                userListTable.requestRepaint();
            }
        });
        
        Button deleteButton = new Button();
        deleteButton.setCaption("Delete Selected");
        deleteButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                if(deleteDialogueWindow.getParent() == null) {
                    selectedUserId = (String)userListTable.getValue();
                    reallyDeleteLabel.setCaption("Really delete User " + selectedUserId + "?");
                    getWindow().addWindow(deleteDialogueWindow);
                }
            }
        });
        
        VerticalLayout formLayout = new VerticalLayout();
        formLayout.addComponent(userForm);
        HorizontalLayout buttonLayout = new HorizontalLayout();
        buttonLayout.addComponent(submitButton);
        buttonLayout.addComponent(deleteButton);
        formLayout.addComponent(buttonLayout);
        addStyleName("wp-users-view");
        addComponent(formLayout);
        
        deleteDialogueWindow.setModal(true);
        deleteDialogueWindow.setWidth(300, Sizeable.UNITS_PIXELS);
        VerticalLayout reallyDeleteVert = new VerticalLayout();
        reallyDeleteVert.setWidth(250, Sizeable.UNITS_PIXELS);
        Button reallyDeleteButton = new Button("Delete");
        reallyDeleteButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                String userId = (String)userListTable.getValue();
                req.deleteUser(userId);
                initUserList();
                getWindow().removeWindow(deleteDialogueWindow);
                selectedUserId = "";
                getApplication().getMainWindow().showNotification("User " + userId + " successfully deleted.", Notification.TYPE_HUMANIZED_MESSAGE);
            }
        });
        Button cancelDeleteButton = new Button("Cancel");
        cancelDeleteButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
               getWindow().removeWindow(deleteDialogueWindow);
               selectedUserId = "";
            }
        });
        reallyDeleteVert.addComponent(reallyDeleteLabel);
        HorizontalLayout deleteDgButtons = new HorizontalLayout();
        deleteDgButtons.addComponent(reallyDeleteButton);
        deleteDgButtons.addComponent(cancelDeleteButton);
        reallyDeleteVert.addComponent(deleteDgButtons);
        deleteDialogueWindow.addComponent(reallyDeleteVert);
    }

    @Override
    public void preView() {
        
    }

    @Override
    public void postView() {

    }

    private class UserFieldFactory extends DefaultFieldFactory {

        @Override
        public Field createField(Item item, Object propertyId, Component uiContext) {
            Field field = super.createField(item, propertyId, uiContext);
            if ("id".equals(propertyId)) {
                TextField id = (TextField) field;

                id.setRequired(true);
                id.setRequiredError("Please insert a username!");
                id.addValidator(new StringLengthValidator("Username has to be between 3 and 15 characters long.", 3, 15, false));
                id.addValidator(new RegexpValidator("\\w+", "You can only use characters, underscores and numbers!"));
                id.setNullRepresentation("");
            }
            return field;
        }
    }
    
    private void initUserListTable() {
        userListTable.setContainerDataSource(userList);
        userListTable.setVisibleColumns(visibleItem);
        userListTable.setSelectable(true);
        userListTable.setImmediate(true);
        userListTable.setWidth(180, Sizeable.UNITS_PIXELS);
    }
    
    private void initUserList () {
        List<User> users = req.listUsers();
        userList.removeAllItems();
        userList.addContainerProperty("Username", String.class, null);
        for (User u : users) {
            Item item = userList.addItem(u.getId());
            item.getItemProperty("Username").setValue(u.getId());
        }
    }
}
